//
//  PresentLayerAndModelLayerViewController.m
//  CoreAnimation
//
//  Created by 张国文 on 16/10/26.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "PresentLayerAndModelLayerViewController.h"

@interface PresentLayerAndModelLayerViewController ()

@property (nonatomic, strong) CALayer *colorLayer1;

@property (nonatomic, strong) CALayer *colorLayer2;

@property (nonatomic, strong) CALayer *colorLayer3;

@end

@implementation PresentLayerAndModelLayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.colorLayer1 = [CALayer layer];
    self.colorLayer1.bounds = CGRectMake(0, 0, 300, 300);
    self.colorLayer1.position = CGPointMake(self.view.frame.size.width / 2, 200);
    self.colorLayer1.backgroundColor = [UIColor blueColor].CGColor;
    [self.view.layer addSublayer:_colorLayer1];
    
    self.colorLayer2 = [CALayer layer];
    self.colorLayer2.bounds = CGRectMake(0, 0, 200, 200);
    self.colorLayer2.position = CGPointMake(self.view.frame.size.width / 2, 200);
    self.colorLayer2.backgroundColor = [UIColor yellowColor].CGColor;
    [self.view.layer addSublayer:_colorLayer2];
    
    self.colorLayer3 = [CALayer layer];
    self.colorLayer3.bounds = CGRectMake(0, 0, 100, 100);
    self.colorLayer3.position = CGPointMake(self.view.frame.size.width / 2, 200);
    self.colorLayer3.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:_colorLayer3];
    
    
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // histTest 如果触摸点不在此范围内返回nil，如果在则返回图层本身
    
    // 经过测试我们发现，colorLayer3.presentationLayer我们每次点击都不一样，那是因为屏幕没秒刷新60次，因此每次的呈现视图的状态就不一样了。呈现视图就是我们看到的视图。
    CGPoint point = [[touches anyObject] locationInView:self.view];
    
    if ([self.colorLayer3.presentationLayer hitTest:point]) {
        NSLog(@"红色");
        // 点击colorLayer3的时候改变颜色
        CGFloat red = arc4random() % 256 / 255.0;
        CGFloat green = arc4random() % 256 / 255.0;
        CGFloat blue = arc4random() % 256 / 255.0;
        self.colorLayer3.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1].CGColor;
    } else {
        
        // 我们在点击不是colorLayer3的时候改变colorLayer3的旋转方向
        [CATransaction begin];
        [CATransaction setAnimationDuration:1.0];
        self.colorLayer3.affineTransform = CGAffineTransformRotate(self.colorLayer3.affineTransform, M_PI_4);
        self.colorLayer3.position = point;
        [CATransaction commit];
        
        if ([self.colorLayer2.presentationLayer hitTest:point]) {
            NSLog(@"黄色");
        } else {
            if ([self.colorLayer1.presentationLayer hitTest:point]) {
                NSLog(@"蓝色");
            }
        }
      

    }

    
}




@end
